package com.nutstudio.feilproject.net;

import com.nutstudio.feilproject.Constant;
import com.nutstudio.feilproject.manager.net_tools.UpLoadProgressInterceptor;
import com.nutstudio.feilproject.manager.net_tools.UploadListener;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 获取RetrofitService实例
 * Created by yangle on 2017/6/27.
 */

public class UploadRetrofitHelper {

    private static UploadRetrofitHelper retrofitHelper;
    private RetrofitService retrofitService;

    public static UploadRetrofitHelper getInstance(UploadListener listener) {
        return retrofitHelper == null ? retrofitHelper = new UploadRetrofitHelper(listener) : retrofitHelper;
    }

    private UploadRetrofitHelper(UploadListener listener) {
        UpLoadProgressInterceptor interceptor = new UpLoadProgressInterceptor(listener);
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
//设置日志Level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
//添加拦截器到OkHttp，这是最关键的
        httpClient.addInterceptor(logging);
        httpClient.addInterceptor(interceptor);


        // 初始化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create()) // json解析
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava
                .client(httpClient.build())
                .build();
        retrofitService = retrofit.create(RetrofitService.class);


    }

    public RetrofitService getRetrofitService() {
        return retrofitService;
    }
}
